package com.lsh.oms.core.service.order;

import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.api.model.es.OrderHeadForEs;
import com.lsh.oms.api.model.order.delivery.OrderSendHeadDTO;
import com.lsh.oms.api.model.status.FreightDto;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.OrderOperateType;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.order.OrderHeadExt;
import com.lsh.oms.core.proxy.service.EsProxy;
import com.lsh.oms.core.proxy.service.TmsProxy;
import com.lsh.oms.core.service.status.impl.ModifyInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Project Name: OrderCancelService
 * 北京链商电子商务有限公司
 *
 * @author wangliutao
 * Date: 18/6/27
 * Package Name: com.lsh.oms.core.service.order
 * Description: 订单取消的service
 */
@Service
public class OrderCancelService {
    private static final Logger logger = LoggerFactory.getLogger(OrderCancelService.class);

    @Autowired
    private OrderUpdateService orderUpdateService;

    @Autowired
    private EsProxy esProxy;

    @Autowired
    private TmsProxy tmsProxy;

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private ModifyInfoService modifyInfoService;

    @Value("${run.system}")
    private String system;

    @Value("${kefu.email.address}")
    private String kfAddress;

    @Value("${short.message.order.project}")
    private String orderProject;

//    /**
//     * 客服电话
//     */
//    @Value("#{'${short.message.service.phones}'.split(',')}")
//    private List<String> phones;


    /**
     * 订单全单捡缺,取消订单
     *
     * @param orderSendHeadDTO 订单号
     * @retrn
     */
    public CommonResult orderAllPickUpShortCancel(OrderSendHeadDTO orderSendHeadDTO, String logSign, Long venderId) {
        Long orderCode = orderSendHeadDTO.getOrder_id();
        logger.info("【订单全单捡缺】 logSign : {}, orderCode : {}", logSign, orderCode);
        OrderHead orderHead = orderQueryService.findByCode(orderCode, false, false);

        if (orderHead == null) {
            return CommonResult.error("订单不存在", "error");
        }

        if (orderHead.getOrderStatus() >= OrderStatus.ORDER_CANCEL_CUSTOMERSERVICE.getIndex()) {
            return CommonResult.success("ok", "success");
        }

        if (orderHead.getOrderStatus() >= OrderStatus.ORDER_DELIVERY.getIndex()) {
            return CommonResult.error("订单状态不允许取消", "error");
        }

        this.fillFreight(orderHead);

        int flag = orderUpdateService.updateOrderStatus(orderCode, null, OrderOperateType.ORDER_CANCEL_BY_CUSTOM_SERVICE, venderId);

        if (flag > 0) {
            this.updateHeadExt(orderCode);

            OrderHeadForEs ohEs = new OrderHeadForEs();
            ohEs.setOrderCode(orderCode);
            ohEs.setOrderStatus(OrderStatus.ORDER_CANCEL_CUSTOMERSERVICE.getIndex());
            if (esProxy.editIndex(ohEs, logSign)) {
                logger.info(orderCode + "订单取消更新es成功");
            }

            Integer sale_model = orderSendHeadDTO.getSale_model();
            Integer delivery_type = orderSendHeadDTO.getDelivery_type();
            int type = 1;
            if (delivery_type == 3) {
                type = 4;
            }

            try {
                tmsProxy.cancelTask(UUID.randomUUID().toString(), orderSendHeadDTO.getOrder_id(), type, venderId);
            } catch (IOException e) {
                logger.error("订单取消tms 失败", e);
            }

        } else {
            return CommonResult.error("订单取消失败", "error");
        }

        return CommonResult.success("ok", "success");
    }

    /**
     * 运费转移
     *
     * @param orderHead
     */
    private void fillFreight(OrderHead orderHead) {

        try {
            Long orderCode = orderHead.getOrderCode();
            Long fillOrderCode = null;
            BigDecimal fillFreight = orderHead.getFreight();

            if (fillFreight == null || fillFreight.compareTo(BigDecimal.ZERO) <= 0) {
                return;
            }
            if (orderHead.getParentOrderCode() == null || orderHead.getParentOrderCode() == 0L) {
                return;
            }

            List<OrderHead> orderHeadList = orderQueryService.findByParentOrderCode(orderHead.getParentOrderCode(), false, false);
            if (CollectionUtils.isEmpty(orderHeadList)) {
                return;
            }

            for (OrderHead head : orderHeadList) {
                if (orderCode.equals(head.getOrderCode())) {
                    continue;
                }

                if (head.getOrderStatus() < OrderStatus.ORDER_CANCEL_CUSTOMERSERVICE.getIndex()) {
                    fillOrderCode = head.getOrderCode();
                    break;
                }
            }

            if (fillOrderCode != null) {

                List<FreightDto> freightList = new ArrayList<>();
                FreightDto zeroFreightDto = new FreightDto();
                zeroFreightDto.setOrderCode(orderCode);
                zeroFreightDto.setFreight(BigDecimal.ZERO);

                FreightDto fillFreightDto = new FreightDto();
                fillFreightDto.setOrderCode(fillOrderCode);
                fillFreightDto.setFreight(fillFreight);

                freightList.add(zeroFreightDto);
                freightList.add(fillFreightDto);

                this.modifyInfoService.modifyFreight(freightList);
            }

        } catch (Exception e) {

        }

    }

    private CommonResult<Object> createResult(String code, String message) {
        CommonResult<Object> commonResult = new CommonResult<>(code, message);
        return commonResult;
    }

    /**
     * @param orderCode
     */
    private void updateHeadExt(Long orderCode) {

        try {
            OrderHead head = orderQueryService.findByCode(orderCode, false, false);
            // TODO 2019-05-09
            OrderHeadExt headExt = new OrderHeadExt();
            headExt.setId(head.getId());
            headExt.setCancelTime(new Date());
            headExt.setCancelRemark("全单拣缺系统取消");
            this.orderUpdateService.updateOrderExt(headExt);
        } catch (Exception e) {
            logger.error(orderCode + " 全单拣缺取消 订单取消设置headExt失败", e);
        }
    }

    /**
     * 订单全单捡缺,取消订单
     *
     * @param orderCode 订单号
     * @return
     */
    public CommonResult orderCancel(Long orderCode, String logSign) {
        logger.info("【预下单订单取消】 logSign : {}, orderCode : {}", logSign, orderCode);
        OrderHead orderHead = orderQueryService.findByCode(orderCode, false, false);

        if (orderHead == null) {
            return new CommonResult(ReturnCode.REQUEST_FAIL, "订单不存在");
        }

        if (orderHead.getOrderStatus() >= OrderStatus.ORDER_CANCEL_CUSTOMERSERVICE.getIndex()) {
            return this.createResult(ReturnCode.REQUEST_SUCCESS, "取消处理成功");
        }

        if (orderHead.getOrderStatus() >= OrderStatus.ORDER_DELIVERY.getIndex()) {
            return new CommonResult(ReturnCode.REQUEST_FAIL, "【预下单订单取消】订单状态不允许取消");
        }

        int flag = orderUpdateService.updateOrderValid(orderCode);

        if (flag > 0) {
            OrderHeadForEs ohEs = new OrderHeadForEs();
            ohEs.setOrderCode(orderCode);
            ohEs.setOrderStatus(OrderStatus.ORDER_CANCEL_CUSTOMERSERVICE.getIndex());
            if (esProxy.deleteIndex(ohEs, logSign)) {
                logger.info("【预下单订单失效】" + orderCode + "订单失效更新es成功");
            }
        } else {
            return new CommonResult(ReturnCode.REQUEST_FAIL, "【预下单订单取消】订单取消失败");
        }

        return this.createResult(ReturnCode.REQUEST_SUCCESS, "取消处理成功");
    }

//    /**
//     * 发送短信
//     *
//     * @param orderCode     订单号
//     * @param customerPhone 客户电话
//     */
//    private void sendShortMsg(String orderCode, String customerPhone) {
//        String message = MessageFormat.format(ShortMessageConstants.CANCEL_TMS_MSG, orderCode);
//
//        ShortMessageModel shortMessage = new ShortMessageModel();
//        shortMessage.setContent(message);
//        List<String> smPhones = new ArrayList<>();
//        //给客户发短信
//        if (StringUtils.isNotBlank(customerPhone)) {
//            smPhones.add(customerPhone);
//        }
//        shortMessage.setPhones(smPhones);
//
//        OmsEventBus.post(shortMessage);
//    }
}
